package com.io.bio;

import com.io.util.CalculatorUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Random;

/**
 * @author hjj
 * @create 2019-11-22 21:56
 */
public class BIOClient {
    private static final int PORT = 8888;
    private static final String IP_ADDRESS = "127.0.0.1";

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            clientReq(i);
        }
    }

    private static void clientReq(int i) {
        Socket socket = null;
        BufferedReader bufferedReader = null;
        PrintWriter writer = null;
        try {
            socket = new Socket(IP_ADDRESS, PORT);
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(socket.getOutputStream(), true);
            String[] operators = {"+", "-", "*", "/"};
            Random random = new Random(System.currentTimeMillis());
            String expression = random.nextInt(10) + operators[random.nextInt(4)] + (random.nextInt(10) + 1);
            System.out.println("BIOClent send: " + expression);
            writer.println(expression); // 向服务器端发送数据
//            System.out.println(i + " 客户端打印返回数据 : " + bufferedReader.readLine());
            String body = null;
            while (true) {
                body = bufferedReader.readLine();
                if (body == null) break;
                System.out.println("BIOClient receive: " + body);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bufferedReader) {
                    bufferedReader.close();
                }
                if (null != socket) {
                    socket.close();
                    socket = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
